<template>
    <div class="manage-page">
        <!-- 页面标题 -->
        <header class="header">商品管理</header>

        <!-- 新增商品模块 -->
        <div class="section">
            <h2 @click="toggleSection('newProduct')">新增商品</h2>
            <div v-show="sections.newProduct" class="content">
                <form @submit.prevent="addProduct" class="add-product-form">
                    <div class="form-group">
                        <label for="name">商品名称:</label>
                        <input v-model="newProduct.name" type="text" id="name" required>
                    </div>
                    <div class="form-group">
                        <label for="description">商品描述:</label>
                        <textarea v-model="newProduct.description" id="description" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="price">价格:</label>
                        <input v-model="newProduct.price" type="number" id="price" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label for="stock">库存:</label>
                        <input v-model="newProduct.stock" type="number" id="stock" required>
                    </div>
                    <div class="form-group">
                        <label for="status">状态:</label>
                        <select v-model="newProduct.status" id="status" required>
                            <option value="1">上架</option>
                            <option value="0">下架</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="image">商品图片:</label>
                        <input type="url" v-model="newProduct.imageUrl" id="imageUrl" required placeholder="图片url">
                        <input type="file" id="image" @change="handleImageUpload" accept="image/*">
                        <img v-if="newProduct.imageUrl" :src="newProduct.imageUrl" alt="商品图片预览" class="image-preview">
                    </div>
                    <button type="submit" class="submit-btn">添加商品</button>
                </form>
            </div>
        </div>

        <!-- 商品管理模块 -->
        <div class="section">
            <h2 @click="toggleSection('product')">商品管理</h2>
            <div v-show="sections.product" class="content">
                <!-- 商品搜索 -->
                <div class="search-bar">
                    <input v-model="searchQuery" type="text" placeholder="请输入商品名称搜索" />
                    <button @click="searchProduct">搜索</button>
                </div>

                <!-- 搜索结果 -->
                <div v-if="searchResults.length > 0" class="product-list">
                    <div v-for="product in searchResults" :key="product.id" class="product-item">
                        <img :src="product.imageUrl || placeholderImage" alt="商品图片" class="product-image" />
                        <div class="product-info">
                            <h3>{{ product.name }}</h3>
                            <p>{{ product.description }}</p>
                            <p>价格: ¥{{ product.price }}</p>
                            <p>库存: {{ product.stock }}</p>
                            <p>状态: {{ product.status === 1 ? "上架" : "下架" }}</p>
                            <button @click="editProduct(product)">修改</button>
                            <button @click="deleteProduct(product.id)">删除</button>
                            <button @click="toggleStatus(product.id)">
                                {{ product.status === 1 ? "下架" : "上架" }}
                            </button>
                            <button @click="addToCarousel(product)">增加到推荐商品</button> <!-- 新增按钮 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 推荐商品管理模块 -->
        <div class="section">
            <h2 @click="toggleSection('carousel')">推荐商品管理</h2>
            <div v-show="sections.carousel" class="content">
                <!-- 推荐商品列表 -->
                <div v-if="carouselItems.length > 0" class="carousel-list">
                    <div v-for="item in carouselItems" :key="item.id" class="carousel-item">
                        <img :src="item.imageUrl" alt="推荐商品图片" class="carousel-image" />
                        <div class="carousel-info">
                            <h3>{{ item.title }}</h3>
                            <p>{{ item.description }}</p>
                            <p>优先级: {{ item.priority }}</p>
                            <p>时间: {{ item.startTime }} - {{ item.endTime }}</p>
                            <button @click="editCarousel(item)">修改</button>
                            <button @click="deleteCarousel(item.id)">删除</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部导航 -->
        <footer class="bottom-bar">
            <div class="nav-icon" @click="navigateTo('/')">首页</div>
            <div class="nav-icon" @click="navigateTo('/seckill')">秒杀</div>
            <div class="nav-icon" @click="navigateTo('/orders')">订单</div>
            <div class="nav-icon" @click="navigateTo('/manage')">管理</div>
        </footer>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            searchQuery: "",
            searchResults: [],
            carouselItems: [],
            sections: {
                newProduct: true,
                product: true,
                carousel: false,
            },
            placeholderImage: "http://example.com/placeholder.jpg",
            newProduct: {
                name: "",
                description: "",
                price: null,
                stock: null,
                status: "1",
                imageUrl: "",
            },
        };
    },
    methods: {
        toggleSection(section) {
            this.sections[section] = !this.sections[section];
        },
        navigateTo(route) {
            this.$router.push(route);
        },
        searchProduct() {
            const productName = this.searchQuery.trim();
            if (!productName) {
                alert("请输入商品名称！");
                return;
            }

            // 请求地址
            const url = `http://localhost:8080/product/getProductByName/${encodeURIComponent(productName)}`;

            // 发起请求
            axios.get(url)
                .then(response => {
                    if (response.data.code === 200) {
                        this.searchResults = response.data.data; // 更新搜索结果
                    } else {
                        alert("查询失败：" + response.data.msg);
                    }
                })
                .catch(error => {
                    console.error("请求失败:", error);
                    alert("查询失败，请稍后重试！");
                });
        },
        searchRecommendedItems() {
            // 请求地址
            const url = "http://localhost:8080/carousel/list";

            // 发起请求
            axios.get(url)
                .then(response => {
                    if (response.data.code === 200) {
                        this.carouselItems = response.data.data; // 更新推荐商品列表
                    } else {
                        alert("查询失败：" + response.data.msg);
                    }
                })
                .catch(error => {
                    console.error("请求失败:", error);
                    alert("查询失败，请稍后重试！");
                });
        },
        addToCarousel(product) {
            // 获取存储在本地的 token
            const token = localStorage.getItem('Authorization');  // 假设 token 存储在 localStorage 中

            if (!token) {
                alert("请先登录！");
                return;
            }

            // 设置请求头 Authorization
            const headers = {
                'Authorization': `${token}`,
            };

            // 请求地址
            const url = "http://localhost:8080/carousel/add";

            // 构造请求参数
            const item = {
                productId: product.id,
                imageUrl: product.imageUrl,
                title: product.name,
                description: product.description,
                status: 1,
                priority: 1,
                startTime: new Date().toISOString(),
                endTime: new Date().toISOString(),
            };

            // 发送请求，将商品添加到推荐商品列表
            axios.post(url, item, { headers })
                .then(response => {
                    if (response.data.code === 200) {
                        alert("商品已成功添加到推荐商品列表！");
                        this.searchRecommendedItems();  // 重新加载推荐商品列表
                    } else {
                        alert("添加失败：" + response.data.msg);
                    }
                })
                .catch(error => {
                    console.error("请求失败:", error);
                    alert("添加失败，请稍后重试！");
                });
        },
        editProduct(product) {
            // 模拟修改商品操作
            console.log("修改商品:", product);
        },
        async deleteProduct(productId) {
            // 模拟删除商品操作
            console.log("删除商品ID:", productId);

            // 请求地址
            const url = `http://localhost:8080/product/delete/${encodeURIComponent(productId)}`;
            console.log("删除商品URL:", url);

            try {
                // 发起请求，传递 Authorization 请求头
                const response = await axios.delete(url, {
                    headers: {
                        'Authorization': localStorage.getItem('Authorization'),
                    }
                });

                // 处理响应
                if (response.data.code === 200) {
                    alert("商品删除成功！");
                    this.searchProduct(); // 刷新商品列表
                } else {
                    alert("删除失败：" + response.data.msg);
                }
            } catch (error) {
                console.error("请求失败:", error);
                alert("请求失败，请稍后重试！");
            }
        },
        toggleStatus(productId) {
            // 模拟上下架切换
            console.log("切换商品状态ID:", productId);
        },
        editCarousel(item) {
            // 模拟修改推荐商品
            console.log("修改推荐商品:", item);

        },
        deleteCarousel(itemId) {
            // 模拟删除推荐商品
            console.log("删除推荐商品ID:", itemId);
        },
        async handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await axios.post('http://localhost:8080/product/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': localStorage.getItem('Authorization'),
                    },
                });

                if (response.data.code === 200) {
                    this.newProduct.imageUrl = response.data.url;
                } else {
                    alert('图片上传失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                alert('图片上传失败，请稍后重试！');
            }
        },

        async addProduct() {
            if (!this.validateForm()) return;

            const token = localStorage.getItem('Authorization');

            try {
                const response = await axios.post('http://localhost:8080/product/add', this.newProduct, {
                    headers: {
                        'Authorization': `${token}`,
                    },
                });

                if (response.data.code === 200) {
                    alert('商品添加成功！');
                    this.resetForm();
                    this.searchProduct(); // 刷新商品列表
                } else {
                    alert('商品添加失败：' + response.data.msg);
                }
            } catch (error) {
                console.error('商品添加失败:', error);
                alert('商品添加失败，请稍后重试！');
            }
        },

        validateForm() {
            if (!this.newProduct.name || !this.newProduct.description || !this.newProduct.price || !this.newProduct.stock) {
                alert('请填写所有必填字段！');
                return false;
            }
            if (this.newProduct.price <= 0) {
                alert('价格必须大于0！');
                return false;
            }
            if (this.newProduct.stock < 0) {
                alert('库存不能为负数！');
                return false;
            }
            return true;
        },

        resetForm() {
            this.newProduct = {
                name: "",
                description: "",
                price: null,
                stock: null,
                status: "1",
                imageUrl: "",
            };
        },
    },
    mounted() {
        this.searchRecommendedItems();
    },
};
</script>

<style scoped>
.manage-page {
    font-family: Arial, sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;
}

.header {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
}

.section {
    width: 100%;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    background-color: #fff;
}

.section h2 {
    font-size: 18px;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
}

.content {
    margin-top: 10px;
}

.product-list,
.carousel-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.product-item,
.carousel-item {
    display: flex;
    gap: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    padding: 10px;
}

.product-image,
.carousel-image {
    width: 80px;
    height: 80px;
    object-fit: cover;
}

.bottom-bar {
    display: flex;
    justify-content: space-around;
    background-color: #f5f5f5;
    padding: 10px 0;
    position: fixed;
    bottom: 0;
    width: 100%;
}

.nav-icon {
    flex: 1;
    text-align: center;
    padding: 10px;
    color: #333;
    font-size: 14px;
    cursor: pointer;
}

.add-product-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    margin-bottom: 5px;
}

.form-group input,
.form-group textarea,
.form-group select {
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

.image-preview {
    max-width: 200px;
    max-height: 200px;
    margin-top: 10px;
}

.submit-btn {
    background-color: #4CAF50;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 3px;
    cursor: pointer;
}

.submit-btn:hover {
    background-color: #45a049;
}
</style>
